#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2020/6/25 15:30
# @file     : redis_client.py
# @Software : PyCharm
# ======================================#
import redis
import json
from flask import current_app


class Redis(object):
    @staticmethod
    def _get_redis(redis_type="StrictRedis"):
        host = current_app.config.get("REDIS_HOST", "127.0.0.1")
        port = current_app.config.get("REDIS_PORT", 6379)
        db = current_app.config.get("REDIS_DB", 0)
        if redis_type == "StrictRedis":
            r = redis.StrictRedis(host=host, port=port, db=db,socket_connect_timeout=1)
        elif redis_type == "Redis":
            r = redis.Redis(host=host, port=port, db=db,socket_connect_timeout=1)
        elif redis_type == "ReidsPool":
            pool = redis.ConnectionPool(host=host, port=port, db=db,socket_connect_timeout=1)
            r = redis.Redis(connection_pool=pool)
        else:
            r = redis.StrictRedis(host, port, db)
        return r

    @classmethod
    def set_json(cls, key, value, expire=None):
        """写入dict"""
        if not isinstance(value, dict):
            raise Exception(f"dict value is required")
        if expire:
            expire_time = expire
        else:
            expire_time = current_app.config.get("REDIS_EXPIRE", 600)
        r = cls._get_redis()
        bytes_value = bytes(json.dumps(value), encoding="utf-8")
        return r.set(key, bytes_value, ex=expire_time)

    @classmethod
    def get_json(cls, key):
        """读取json"""
        r = cls._get_redis()
        value = r.get(key)
        json_value = json.loads(value.decode("utf-8")) if value else value
        return json_value

    @classmethod
    def set(cls, key, value, expire=None):
        """写入键值对"""
        if expire:
            expire_time = expire
        else:
            expire_time = current_app.config.get("REDIS_EXPIRE", 600)
        r = cls._get_redis()
        return r.set(key, value, ex=expire_time)

    @classmethod
    def get(cls, key):
        """读取键值对内容"""
        r = cls._get_redis()
        value = r.get(key)
        return value.decode("utf-8") if value else value

    @classmethod
    def delete(cls, *names):
        """删除一个或多个"""
        r = cls._get_redis()
        return r.delete(*names)

    @classmethod
    def hset(cls, name, key, value):
        """写入hash表"""
        r = cls._get_redis()
        return r.hset(name, key, value)

    @classmethod
    def hmset(cls, key, *value):
        """获取指定hash表所有给定字段的值"""
        r = cls._get_redis()
        value = r.hmset(key, *value)
        return value

    @classmethod
    def hget(cls, name, key):
        """读取指定hash表值"""
        r = cls._get_redis()
        value = r.hget(name, key)
        return value.decode("utf-8") if value else value

    @classmethod
    def hgetall(cls, name):
        """获取指定hash表所有值"""
        r = cls._get_redis()
        return r.hgetall(name)

    @classmethod
    def hdel(cls, name, key):
        """删除指定hash表键值"""
        r = cls._get_redis()
        return r.hdel(name, key)

    @classmethod
    def keys(cls):
        """获取所有的keys"""
        r=cls._get_redis()
        return r.keys()

    @classmethod
    def expire(cls, name, expire=None):
        """设置过期时间"""
        if expire:
            expire_time = expire
        else:
            expire_time = current_app.config.get("REDIS_EXPIRE")
        r = cls._get_redis()
        return r.expire(name, expire_time)
